# -*- coding: utf-8 -*-
"""
@Time    : 2024/7/12 20:35 
@Author  : ZhangShenao 
@File    : 2.使用OutputFixingParser自动修复解析器.py 
@Desc    : 使用OutputFixingParser,自动修复解析器,可以自动修复格式异常的输出

在OutputFixingParser内部,调用了原有的PydanticOutputParser尝试解析
如果解析成功,就直接返回
如果解析失败,它会将格式错误的输出以及格式化的指令传递给,并要求LLM进行相关的修复

"""
import os
from typing import List

import dotenv
from langchain.output_parsers import OutputFixingParser
from langchain_core.output_parsers import PydanticOutputParser
from langchain_core.pydantic_v1 import BaseModel, Field
from langchain_openai import ChatOpenAI

dotenv.load_dotenv()


class Actor(BaseModel):
    name: str = Field(description="name of an actor")
    film_names: List[str] = Field(description="list of names of films they starred in")


actor_query = "Generate the filmography for a random actor."

parser = PydanticOutputParser(pydantic_object=Actor)

misformatted = "{'name': 'Tom Hanks', 'film_names': ['Forrest Gump']}"

new_parser = OutputFixingParser.from_llm(parser=parser, llm=ChatOpenAI(openai_api_base=os.getenv('OPENAI_API_BASE')))

print(new_parser.parse(misformatted))
